﻿using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;

namespace FastNET.CleanAct.Tools.HomeTemplateEditor.Dialogs
{
    internal partial class ValidateCertDialog : Form
    {
        public ValidateCertDialog()
        {
            InitializeComponent();
        }

        public X509Certificate2 Certificate { get; set; }
        public string FileName { get; set; }

        private void LoadCertInfo()
        {
            PublisherField.Text = Certificate.FriendlyName;

            X509Chain ch = new X509Chain
                           {
                               ChainPolicy = { RevocationMode = X509RevocationMode.Online }
                           };

            if (!ch.Build(Certificate))
            {
                ReasonField.Text = string.Empty;
                foreach (X509ChainStatus status in ch.ChainStatus)
                {
                    if (status.Status == X509ChainStatusFlags.NoError)
                    {
                        continue;
                    }

                    ReasonField.Text += status.StatusInformation + " ";
                }
            }
            else
            {
                ReasonField.Text = "Certificate is Valid";
            }
        }

        private void ValidateCertDialog_Load(object sender, System.EventArgs e)
        {
            if (Certificate != null)
            {
                LoadCertInfo();
                CertificateButton.Enabled = true;
            }
            else
            {
                CertificateButton.Enabled = false;
            }

            FileField.Text = FileName;
        }

        private void CertificateButton_Click(object sender, System.EventArgs e)
        {
            if (Certificate != null)
            {
                X509Certificate2UI.DisplayCertificate(Certificate);
            }
        }


    }
}
